package edu.hawaii.jmotif.sequitur.logic;

import java.util.StringTokenizer;

/**
 * Sort of a stand-alone factory to digesting strings with Sequitur.
 * 
 * @author psenin
 * 
 */
public class SequiturFactory {

  /**
   * Digests a string of symbols separated by space.
   * 
   * @param string The string to digest. Symbols expected to be separated by space.
   * 
   * @return The top rule handler.
   */
  public static SAXRule digest(String string) {

    SAXRule resRule = new SAXRule();
    SAXRule.numRules = 0;
    SAXSymbol.theDigrams.clear();

    StringTokenizer st = new StringTokenizer(string, " ");

    // while there are tokens
    while (st.hasMoreTokens()) {

      // extract next token
      SAXTerminal symbol = new SAXTerminal(st.nextToken());

      // append to the end of the current sequitur string
      // ... As each new input symbol is observed, append it to rule S....
      resRule.last().insertAfter(symbol);

      // once appended, check if the resulting digram is new or recurrent
      //
      // ... Each time a link is made between two symbols if the new digram is repeated elsewhere
      // and the repetitions do not overlap, if the other occurrence is a complete rule,
      // replace the new digram with the non-terminal symbol that heads the rule,
      // otherwise,form a new rule and replace both digrams with the new non-terminal symbol
      // otherwise, insert the digram into the index...
      resRule.last().p.check();
    }

    return resRule;
  }

}
